<template>
  <GlobalDrawer
    v-model="drawerVisible"
    title="添加销售机会"
    size="80%"
    :show-footer-buttons="true"
    @confirm="handleSubmit"
    @cancel="handleCancel"
  >
    <div class="trace-form-container">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="120px"
        class="trace-form"
      >
        <el-form-item label="发现日期" prop="discovery_date">
          <el-date-picker
            v-model="formData.discovery_date"
            type="date"
            placeholder="选择日期"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="线索类型" prop="category">
          <el-select v-model="formData.category" placeholder="请选择线索类型">
            <el-option label="案件委托" value="1" />
            <el-option label="法务需求" value="2" />
            <el-option label="法务专项" value="3" />
          </el-select>
        </el-form-item>

        <el-form-item label="线索等级" prop="level">
          <el-select v-model="formData.level" placeholder="请选择线索等级">
            <el-option label="A级" value="1" />
            <el-option label="B级" value="2" />
            <el-option label="C级" value="3" />
          </el-select>
        </el-form-item>

        <!-- 负责人字段已移除，操作人员自动设为线索的发现人（负责人） -->

        <!-- 服务类型字段已移除，数据表中不存在该字段 -->

        <el-form-item label="线索状态" prop="status">
          <el-select v-model="formData.status" placeholder="请选择线索状态">
            <el-option
              v-for="option in statusOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="线索描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="4"
            placeholder="请输入线索描述"
          />
        </el-form-item>
      </el-form>
    </div>
  </GlobalDrawer>
</template>

<script setup lang="ts">
  import { ref, reactive, computed, watch } from 'vue'
  import { ElMessage } from 'element-plus'
  import { DocumentAdd } from '@element-plus/icons-vue'
  import GlobalDrawer from '@/components/common/GlobalDrawer.vue'
  import { opportunityApi } from '@/api/crm/opportunity'
  import type { FormInstance } from 'element-plus'

  // Props
  interface Props {
    modelValue: boolean
    customerId?: string | number
  }

  const props = withDefaults(defineProps<Props>(), {
    modelValue: false,
    customerId: undefined,
  })

  // Emits
  const emit = defineEmits<{
    (e: 'update:modelValue', value: boolean): void
    (e: 'success'): void
  }>()

  // Form reference
  const formRef = ref<FormInstance>()

  // 线索状态选项映射
  const statusOptions = [
    { label: '有效', value: 1 },
    { label: '已转化', value: 2 },
    { label: '已失效', value: 3 },
  ]

  // 表单数据
  const formData = reactive({
    discovery_date: '',
    category: '',
    level: '',
    status: 1, // 默认状态为有效
    description: '',
    customer_id: Number(props.customerId) || undefined,
  })

  // 表单验证规则
  const rules = reactive({
    discovery_date: [{ required: true, message: '请选择发现日期', trigger: 'change' }],
    category: [{ required: true, message: '请选择线索类型', trigger: 'change' }],
    level: [{ required: true, message: '请选择线索等级', trigger: 'change' }],
    description: [{ required: true, message: '请输入线索描述', trigger: 'blur' }],
  })

  // 抽屉可见性
  const drawerVisible = computed({
    get: () => props.modelValue,
    set: value => emit('update:modelValue', value),
  })

  // 监听customerId变化
  watch(
    () => props.customerId,
    newVal => {
      if (newVal) {
        formData.customer_id = Number(newVal) || undefined
      }
    },
    { immediate: true }
  )

  // 重置表单
  const resetForm = () => {
    formRef.value?.resetFields()
    Object.assign(formData, {
      discovery_date: '',
      category: '',
      level: '',
      status: 1,
      description: '',
      customer_id: Number(props.customerId) || undefined,
    })
  }

  // 处理取消
  const handleCancel = () => {
    formRef.value?.resetFields()
    drawerVisible.value = false
  }

  // 处理提交表单
  const handleSubmit = async () => {
    try {
      await formRef.value?.validate()

      // 转换类型以匹配Opportunity接口，确保discovery_date始终有有效整数值
      // 注意：将日期转换为秒级时间戳（除以1000），符合项目规范
      const submitData = {
        ...formData,
        category: formData.category ? Number(formData.category) : undefined,
        level: formData.level ? Number(formData.level) : undefined,
        discovery_date: formData.discovery_date
          ? Math.floor(new Date(formData.discovery_date).getTime() / 1000)
          : 0,
      }

      // 强制确保discovery_date是数字类型，防止空字符串被提交
      submitData.discovery_date = Number(submitData.discovery_date) || 0

      // 使用实际的API调用
      const result = await opportunityApi.addOpportunity(submitData)

      ElMessage.success('添加成功')
      formRef.value?.resetFields()
      drawerVisible.value = false
      emit('success')
    } catch (error) {
      ElMessage.error('添加线索失败，请重试')
    }
  }

  // 暴露方法给父组件
  defineExpose({
    resetForm,
  })
</script>

<style scoped lang="scss">
  .trace-form-container {
    padding: 0;
  }

  .trace-form {
    padding: 20px;
  }

  :deep(.el-form-item) {
    margin-bottom: 20px;
  }

  :deep(.el-input__wrapper) {
    border-radius: 4px;
  }

  // 响应式布局调整
  @media (max-width: 768px) {
    .trace-form {
      padding: 10px;
    }

    :deep(.el-form--label-right) {
      .el-form-item__label {
        text-align: left;
      }
    }
  }
</style>
